/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  LeaderErrorTaskListFragment.java   
 * @Package com.jiyi.activity.leader   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-10-30 下午3:28:57   
 * @version V1.0     
 */
package com.jiyi.activity.leader;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jiyi.adapter.DividerItemDecoration;
import com.jiyi.adapter.recyclerview.MultiItemTypeAdapter;
import com.jiyi.adapter.recyclerview.base.ItemViewDelegate;
import com.jiyi.adapter.recyclerview.base.ViewHolder;
import com.jiyi.adapter.recyclerview.wrapper.EmptyWrapper;
import com.jiyi.bean.maintenance.NewErrorBean;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.event.ErrorTaskListEvent;
import com.jiyi.inteface.OnRcvScrollListener;
import com.jiyi.inteface.WebApi;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @ClassName: LeaderErrorTaskListFragment
 * @Description:TODO(这里用一句话描述这个类的作用)
 * @author: HYM
 * @date: 2017-10-30 下午3:28:57
 * 
 */
public class LeaderNewErrorTaskListFragment extends Fragment implements
		OnRefreshListener {
	LayoutInflater inflater;
	@BindView(R.id.mainList)
	RecyclerView mListView;
	@BindView(R.id.refreshLayout)
	SwipeRefreshLayout refreshLayout;
	EmptyWrapper adapter;
	ViewGroup container;
	int type;
	private List<NewErrorBean> dataList = new ArrayList<NewErrorBean>();
	Dialog dialog;

	// 是否刷新模式
	boolean isRefresh = false;
	int pageNo = 1;// 页码
	private final int LOAD_DATA = 5; // 加载数据事件
	private boolean loadfinish = true; // 指示数据是否加载完成

	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, Bundle savedInstanceState) {
		View view = inflater
				.inflate(R.layout.fragment_all_wx_task, null, false);
		ButterKnife.bind(this, view);
		this.inflater = inflater;
		this.container = container;
		init();
		return view;
	}

	@Subscribe
	public void onErrorTaskListEvent(ErrorTaskListEvent errorTaskListEvent) {
		int position = errorTaskListEvent.position;
		int func = errorTaskListEvent.func;
		int recType = errorTaskListEvent.type;
		if (recType == type) {
			switch (func) {
			case 1:
				// 完成一个申报
				dataList.remove(position);
				adapter.notifyDataSetChanged();
				break;
			case 2:
				// 完成一个派发
				dataList.remove(position);
				adapter.notifyDataSetChanged();
				break;
			default:
				break;
			}
		}

	}

	private void init() {
		setAdapter();
		onRefresh();
		EventBus.getDefault().register(this);
	}

	@Override
	public void onDestroy() {
		EventBus.getDefault().unregister(this);
		super.onDestroy();
	}

	private void setAdapter() {
		// 设置refreshLayout的监听
		refreshLayout.setColorSchemeColors(Color.RED, Color.YELLOW, Color.BLUE,
				Color.GREEN);
		refreshLayout.setOnRefreshListener(this);

		mListView.setLayoutManager(new LinearLayoutManager(getContext()));
		mListView.addItemDecoration(new DividerItemDecoration(getContext(),
				DividerItemDecoration.VERTICAL_LIST, getResources()
						.getDrawable(R.drawable.drvice_10)));

		MultiItemTypeAdapter multiItemTypeAdapter = new MultiItemTypeAdapter(
				getContext(), dataList);
		multiItemTypeAdapter.addItemViewDelegate(new NewErrorDelagate());
		multiItemTypeAdapter.addItemViewDelegate(new HasFinishDelagate());

		adapter = new EmptyWrapper(multiItemTypeAdapter);

		View emptyView = inflater.inflate(R.layout.empty_view_text_and_image,
				container, false);
		ImageView ivEmptyTip = (ImageView) emptyView
				.findViewById(R.id.ivEmptyTip);
		TextView tvEmptyTip = (TextView) emptyView
				.findViewById(R.id.tvEmptyTip);
		ivEmptyTip.setImageResource(R.mipmap.tip_empty_huodong);
		tvEmptyTip.setText(R.string.NO_DATA);
		adapter.setEmptyView(emptyView);

		mListView.setAdapter(adapter);
		adapter.notifyDataSetChanged();
		mListView.addOnScrollListener(new OnRcvScrollListener() {
			@Override
			public void onBottom() {
				super.onBottom();
				if (loadfinish) {
					Log.e("加载到底部 pageNo = ", pageNo + "");
					Log.e("加载到底部 list size = ", dataList.size() + "");
					loadMore();
				}

			}
		});
	}

	public class NewErrorDelagate implements ItemViewDelegate<NewErrorBean> {

		@Override
		public int getItemViewLayoutId() {
			return R.layout.item_equip_error_new;
		}

		@Override
		public boolean isForViewType(NewErrorBean item, int position) {
			return item.getType() == 0;
		}

		@Override
		public void convert(final ViewHolder holder, final NewErrorBean task,
				final int position) {
			holder.setText(R.id.tvCompany, task.getCompany_name());
			holder.setText(R.id.tvDate, task.getError_time());
			holder.setNewErrorTaskAdapter(R.id.childListView, task.getGetInfo(),
					type, position);
			holder.setOnClickListener(R.id.tvAssign, new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent = new Intent(v.getContext(),
							LeaderErrorTaskAssignActivity.class);
					intent.putExtra("cfid", task.getCfid());
					intent.putExtra("owner_id", task.getCompany_id());
					intent.putExtra("owner_name", task.getCompany_name());
					intent.putExtra("position", position);

					v.getContext().startActivity(intent);
				}
			});

			holder.setOnClickListener(R.id.rlExtend, new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (v.getTag() == null) {
						holder.setVisible(R.id.childListView, true);
						v.setTag("extend");
					} else {
						holder.setVisible(R.id.childListView, false);
						v.setTag(null);
					}
				}
			});

		}
	}


	public class HasFinishDelagate implements ItemViewDelegate<NewErrorBean> {

		@Override
		public int getItemViewLayoutId() {
			return R.layout.item_equip_error_assign;
		}

		@Override
		public boolean isForViewType(NewErrorBean item, int position) {
			return item.getType() == 4;
		}

		@Override
		public void convert(final ViewHolder holder, final NewErrorBean task,
				int position) {
			holder.setText(R.id.tvCompany, task.getCompany_name());
			holder.setText(R.id.tvDate, task.getError_time());
			
		}
	}

	/**
	 * @author: HYM
	 * @Title: doDeclare
	 * @Description: TODO(申报动作)
	 * @param cfid
	 * @param position
	 * @param type
	 *            void
	 * @date: 2017-9-25
	 */
	void doDeclare(String cfid, final int position, final int type) {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		params.put("cfid", cfid);

		VolleyRequest.StringRequestPost(getContext(),
				WebApi.MAINTENANCE_LEADER_ERROR_TASK_LIST_DECLARE, "", params,
				new StringInterface(getContext()) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								ToastUtil.getInstances().showMsg(info);
								EventBus.getDefault().post(
										new ErrorTaskListEvent(type, position,
												1));
							} else if (status.equals("404")
									&& info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg(
										"尚未登录或该用户在其他地方登录，请重新登录！");
								// 清除环信登录
								UserHelp.getInstance().clearUser(
										AppBase.Context, true);
								return;
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							// hideDialog(dialog);
						}

					}

					@Override
					public void stringError(VolleyError error) {
						// hideDialog(dialog);
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});
	}

	private void getData() {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		params.put("p", pageNo + "");
		VolleyRequest.StringRequestPost(getContext(),
				WebApi.MAINTENANCE_LEADER_NEW_ERROR_TASK_LIST, "", params,
				new StringInterface(getContext()) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");
								List<NewErrorBean> temp = new Gson().fromJson(
										data, new TypeToken<List<NewErrorBean>>() {
										}.getType());

								if (isRefresh) {
									dataList.clear();
								}

								if (temp.size() > 0) {
									dataList.addAll(temp);
									pageNo++;
								} else {

								}

								adapter.notifyDataSetChanged();
								loadfinish = true; // 加载完成
							} else if (status.equals("404")
									&& info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg(
										"尚未登录或该用户在其他地方登录，请重新登录！");
								// 清除环信登录
								UserHelp.getInstance().clearUser(
										AppBase.Context, true);
								return;
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							refreshLayout.setRefreshing(false);
						}
					}

					@Override
					public void stringError(VolleyError error) {
						refreshLayout.setRefreshing(false);
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});
	}

	@Override
	public void onRefresh() {
		isRefresh = true;
		pageNo = 1;
		mHandler.sendEmptyMessage(LOAD_DATA);
	}

	/**
	 * 处理中心
	 */
	Handler mHandler = new Handler() {
		public void dispatchMessage(android.os.Message msg) {
			switch (msg.what) {
			case LOAD_DATA:
				if (loadfinish) {
					loadfinish = false;
					getData();
				}
				break;
			default:
				break;
			}
		};
	};

	/**
	 * 作者：hym 日期：2017-4-6 描述：加载更多数据
	 */
	void loadMore() {
		isRefresh = false;
		mHandler.sendEmptyMessage(LOAD_DATA);
	}
}
